package cn.lyjuan.first.netty.demo._5_netty_heartbeat.server.handler;

import cn.lyjuan.first.netty._4_netty_serialize.cst.MessageConst;
import cn.lyjuan.first.netty._4_netty_serialize.msg.MyMessage;
import cn.lyjuan.first.netty.demo._5_netty_heartbeat.cst.HeartbeatConst;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;

public class ServerHandler extends SimpleChannelInboundHandler<MyMessage>
{
    private static Logger log = LogManager.getLogger(ServerHandler.class);

    private static MyMessage HEART_MSG = new MyMessage(HeartbeatConst.HEAD_HEART, "", MessageConst.FOOT);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyMessage msg) throws Exception
    {
        InetSocketAddress host = (InetSocketAddress) ctx.channel().remoteAddress();
        log.info("server receive from " + host.getHostName() + ":" + host.getPort() + ": " + msg);

        // 回写
        ctx.writeAndFlush(HEART_MSG);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        InetSocketAddress host = (InetSocketAddress) ctx.channel().remoteAddress();
        log.info("connect from " + host.getHostName() + ":" + host.getPort());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        InetSocketAddress host = (InetSocketAddress) ctx.channel().remoteAddress();
        log.info("disconnect from " + host.getHostName() + ":" + host.getPort());
        super.channelInactive(ctx);
    }
}
